package com.remotephone.myapplication

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Rect
import android.hardware.display.DisplayManager
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.*
import android.util.Log
import android.view.Display
import android.view.PixelCopy
import androidx.core.app.NotificationCompat
import java.io.File
import java.io.FileOutputStream

class PixelCopyScreenshotService : Service() {
    
    private var mediaProjection: MediaProjection? = null
    private var resultCode: Int = 0
    private var resultData: Intent? = null
    
    private val binder = ScreenshotBinder()
    
    // 回调接口
    interface ScreenshotCallback {
        fun onScreenshotTaken(path: String?)
    }
    
    companion object {
        private const val TAG = "PixelCopyScreenshot"
        private const val NOTIFICATION_ID = 3
        private const val CHANNEL_ID = "pixelcopy_service_channel"
        
        const val ACTION_START_PROJECTION = "START_PROJECTION"
        const val ACTION_TAKE_SCREENSHOT = "TAKE_SCREENSHOT"
        const val ACTION_STOP_PROJECTION = "STOP_PROJECTION"
        
        const val EXTRA_RESULT_CODE = "result_code"
        const val EXTRA_RESULT_DATA = "result_data"
        
        private var callback: ScreenshotCallback? = null
        
        fun setCallback(cb: ScreenshotCallback?) {
            callback = cb
        }
    }
    
    inner class ScreenshotBinder : Binder() {
        fun getService(): PixelCopyScreenshotService = this@PixelCopyScreenshotService
    }
    
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        
        when (intent?.action) {
            ACTION_START_PROJECTION -> {
                resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, Activity.RESULT_CANCELED)
                resultData = intent.getParcelableExtra(EXTRA_RESULT_DATA)
                startMediaProjection()
            }
            ACTION_TAKE_SCREENSHOT -> {
                takeScreenshotWithPixelCopy()
            }
            ACTION_STOP_PROJECTION -> {
                stopMediaProjection()
                stopSelf()
            }
        }
        
        return START_STICKY
    }
    
    override fun onBind(intent: Intent?): IBinder = binder
    
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "PixelCopy截图服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "使用PixelCopy API处理屏幕截图"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("PixelCopy截图服务运行中")
            .setContentText("注意: PixelCopy仅支持Surface/Window截图，不支持全屏Display截图")
            .setSmallIcon(android.R.drawable.ic_menu_camera)
            .setOngoing(true)
            .build()
    }
    
    private fun startMediaProjection() {
        if (resultCode != Activity.RESULT_OK || resultData == null) {
            Log.e(TAG, "Invalid result for MediaProjection")
            return
        }
        
        try {
            val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData!!)
            Log.d(TAG, "MediaProjection started successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error starting MediaProjection", e)
        }
    }
    
    private fun takeScreenshotWithPixelCopy() {
        Log.d(TAG, "Starting PixelCopy screenshot...")
        
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
                // Android 13+ (API 33+)
                takeScreenshotAPI33Plus()
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                // Android 10-12 (API 29-32)
                takeScreenshotAPI29Plus()
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
                // Android 8-9 (API 26-28)
                takeScreenshotAPI26Plus()
            }
            else -> {
                // Android 7及以下，不支持PixelCopy
                Log.w(TAG, "PixelCopy not supported on API ${Build.VERSION.SDK_INT}")
                fallbackToMediaProjection()
            }
        }
    }
    
    private fun takeScreenshotAPI33Plus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            try {
                Log.d(TAG, "PixelCopy API for Display screenshots is not available directly")
                Log.d(TAG, "PixelCopy is designed for Surface/Window copying, not Display capture")
                fallbackToMediaProjection()
                
            } catch (e: Exception) {
                Log.e(TAG, "Error with PixelCopy API 33+", e)
                fallbackToMediaProjection()
            }
        }
    }
    
    private fun takeScreenshotAPI29Plus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            try {
                Log.d(TAG, "PixelCopy does not support direct Display capture on API 29+")
                Log.d(TAG, "PixelCopy requires a Surface or Window source, not Display")
                fallbackToMediaProjection()
                
            } catch (e: Exception) {
                Log.e(TAG, "Error with PixelCopy API 29+", e)
                fallbackToMediaProjection()
            }
        }
    }
    
    private fun takeScreenshotAPI26Plus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
                // Android 8-9 需要使用Surface方式，比较复杂
                Log.d(TAG, "API 26-28 requires Surface-based PixelCopy, falling back to MediaProjection")
                fallbackToMediaProjection()
                
            } catch (e: Exception) {
                Log.e(TAG, "Error with PixelCopy API 26+", e)
                fallbackToMediaProjection()
            }
        }
    }
    
    private fun fallbackToMediaProjection() {
        Log.d(TAG, "PixelCopy API 限制说明:")
        Log.d(TAG, "- PixelCopy主要用于从Surface/SurfaceView/Window复制像素")
        Log.d(TAG, "- 不支持直接从Display截取全屏内容")
        Log.d(TAG, "- 无法绕过应用层悬浮窗进行深层截图")
        Log.d(TAG, "- 建议使用MediaProjection或系统shell命令替代")
        
        // 创建说明文件
        createPixelCopyExplanationFile()
        
        callback?.onScreenshotTaken(null)
    }
    
    private fun createPixelCopyExplanationFile() {
        try {
            val explanationDir = File(cacheDir, "screenshots")
            if (!explanationDir.exists()) {
                explanationDir.mkdirs()
            }
            
            val explanationFile = File(explanationDir, "pixelcopy_explanation.txt")
            explanationFile.writeText("""
                PixelCopy API 说明
                ==================
                
                PixelCopy API 的实际用途：
                1. 从SurfaceView复制像素数据
                2. 从特定Window复制内容
                3. 从GL Surface复制渲染结果
                
                PixelCopy API 的限制：
                1. 无法直接截取整个Display
                2. 无法绕过系统级悬浮窗
                3. 需要目标Surface的引用
                4. 主要用于游戏/视频应用内部截图
                
                对于全屏截图，建议使用：
                - MediaProjection API (需要用户授权)
                - Shell命令 screencap (需要系统权限)
                - 系统截图快捷键 (手动操作)
                
                生成时间: ${System.currentTimeMillis()}
            """.trimIndent())
            
            Log.d(TAG, "PixelCopy explanation saved: ${explanationFile.absolutePath}")
            
        } catch (e: Exception) {
            Log.e(TAG, "Error creating explanation file", e)
        }
    }
    
    private fun saveBitmapToFile(bitmap: Bitmap, prefix: String = ""): String? {
        return try {
            val screenshotsDir = File(cacheDir, "screenshots")
            if (!screenshotsDir.exists()) {
                screenshotsDir.mkdirs()
            }
            
            val timestamp = System.currentTimeMillis()
            val screenshotFile = File(screenshotsDir, "${prefix}pixelcopy_screenshot_$timestamp.png")
            
            FileOutputStream(screenshotFile).use { out ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            }
            
            Log.d(TAG, "PixelCopy screenshot saved: ${screenshotFile.absolutePath}")
            screenshotFile.absolutePath
            
        } catch (e: Exception) {
            Log.e(TAG, "Error saving PixelCopy screenshot", e)
            null
        }
    }
    
    private fun stopMediaProjection() {
        mediaProjection?.stop()
        mediaProjection = null
    }
    
    override fun onDestroy() {
        stopMediaProjection()
        super.onDestroy()
    }
} 